import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpHeaders, HttpResponse } from "@angular/common/http";
import { __values } from 'tslib';


@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent {
  public modal: any;
  public modal1: any;
  public modal2: any;
  public rooms: any;
  public token: any;
  public name: any = '';
  public error: any = false;
  public empty: any = false;
  public chooseRoom: any = '';
  public slides: any;
  public dots: any;
  public message: any = false;
  public type: any = 'success';
  public text: any = '登录成功';


  change() {
    let nameDom: any = document.getElementById('name');
    this.name = nameDom.value;
    this.empty = false;
  }

  show() {
    this.modal.style.display = "block";
  }

  show_method() {
    this.showSlides(this.slideIndex);
    this.modal1.style.display = "block";
  }

  close() {
    this.modal.style.display = "none";
    this.name = '';
  }

  close1() {
    this.modal1.style.display = "none";
  }

  setRoom(name: any) {
    this.chooseRoom = name;
  }

  re_enter(){
    this.modal2.style.display = "none";
    this.name = '';
    this.router.navigateByUrl('game');
  }

  enter() {
    if (this.chooseRoom == '') {
      alert("请选择一个房间");
      return;
    } else {
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
      };

      var api = "http://124.221.112.204:3389/room/enter";
      this.http.post(api,
        {
          username: sessionStorage.getItem("username"),
          room: this.chooseRoom,
          time: this.dateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
        }, httpOptions).subscribe(async (response: any) => {
          if (response.code == 200) {
            sessionStorage.setItem("room", this.chooseRoom);
            setTimeout(() => {
              this.router.navigateByUrl('game');
              // window.location.href = "http://localhost:4200/game"
            }, 500);
          }else{
            this.modal2.style.display = "block";
            setTimeout(() => {
              this.message = false;
            }, 2000);
          }
        });
      var f: any = document.getElementById('iframeId');
      // 触发子页面的监听事件
      f.contentWindow.postMessage({ room: this.chooseRoom }, '*');
    }
  }

  room() {
    if (this.name == '') {
      this.empty = true;
      return;
    } else {
      const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
      };

      var api = "http://124.221.112.204:3389/room/new";
      this.http.post(api,
        {
          creator: sessionStorage.getItem("username"),
          name: this.name,
          time: this.dateFormat(new Date(), 'YYYY-MM-DD HH:mm:ss')
        }, httpOptions).subscribe(async (response: any) => {
          if (response.code == 200) {
            sessionStorage.setItem("room", this.name);

            new Promise((r) => {
              var f: any = document.getElementById('iframeId');
              // 触发子页面的监听事件
              f.contentWindow.postMessage({ room: this.name }, '*');
            })
              .then(() => { })
              .then(() => { this.router.navigateByUrl('game') })
            // this.router.navigateByUrl('game')
            setTimeout(() => {
              this.router.navigateByUrl('game');
              // window.location.href = "http://localhost:4200/game"
            }, 200)
          } else {
            this.message = true;
            this.type = 'failure';
              this.text = '房间已存在';
            setTimeout(() => {
              this.message = false;
            }, 2000);
          }
        });
    }
  }

  ngAfterViewInit() {
    var f: any = document.getElementById('iframeId');
    // 触发子页面的监听事件
    f.contentWindow.postMessage({ model: sessionStorage.getItem("model") }, '*');
    f.contentWindow.postMessage({ color: sessionStorage.getItem("color") }, '*');
    f.contentWindow.postMessage({ username: sessionStorage.getItem("username") }, '*');
  }

  ngOnInit() {
    var f: any = document.getElementById('iframeId');
    // 触发子页面的监听事件
    f.contentWindow.postMessage({ model: sessionStorage.getItem("model") }, '*');
    f.contentWindow.postMessage({ color: sessionStorage.getItem("color") }, '*');
    f.contentWindow.postMessage({ username: sessionStorage.getItem("username") }, '*');

    this.slides = document.getElementsByClassName("mySlides");
    this.dots = document.getElementsByClassName("dot");
    this.token = sessionStorage.getItem("token");
    this.modal = document.getElementById('id01');
    this.modal1 = document.getElementById('id02');
    this.modal2 = document.getElementById('id03');
    if (!sessionStorage.getItem("username")) {
      alert('请先登录');
      this.router.navigateByUrl('login');
    }

    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
    };

    var api = "http://124.221.112.204:3389/room/all";
    this.http.get(api, httpOptions).subscribe((response: any) => {
      if (response.code == 200) {
        this.rooms = response.data;
      }
    });
  }

  flash() {
    this.chooseRoom = '';
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'token': this.token })
    };

    var api = "http://124.221.112.204:3389/room/all";
    this.http.get(api, httpOptions).subscribe((response: any) => {
      if (response.code == 200) {
        this.rooms = response.data;
      }
    });
  }

  constructor(public http: HttpClient, private router: Router) { }

  logout() {
    sessionStorage.clear();
    this.router.navigateByUrl('login');
  }


  public slideIndex: any = 1;


  // Next/previous 控件
  plusSlides(n: any) {
    this.showSlides(this.slideIndex += n);
  }

  // 缩略图图像控件
  currentSlide(n: any) {
    this.showSlides(n);
  }

  showSlides(n: any) {
    var i;

    if (n > this.slides.length) { this.slideIndex = 1 }
    if (n < 1) { this.slideIndex = this.slides.length }
    for (i = 0; i < this.slides.length; i++) {
      this.slides[i].style.display = "none";
    }
    for (i = 0; i < this.dots.length; i++) {
      this.dots[i].className = this.dots[i].className.replace(" active", "");
    }
    this.slides[this.slideIndex - 1].style.display = "block";
    this.dots[this.slideIndex - 1].className += " active";
  }

  goToPersonalCenter() {
    this.router.navigateByUrl('personal-center');
  }

  /*
  timestamp: 13位时间戳 | new Date() | Date()
  console.log(dateFormat(1714528800000, 'YY-MM-DD HH:mm:ss'))
  format => YY：年，M：月，D：日，H：时，m：分钟，s：秒，SSS：毫秒
*/
  dateFormat(timestamp: number | string | Date, format = 'YYYY-MM-DD HH:mm:ss'): string {
    var date = new Date(timestamp)
    function fixedTwo(value: number): string {
      return value < 10 ? '0' + value : String(value)
    }
    var showTime = format
    if (showTime.includes('SSS')) {
      const S = date.getMilliseconds()
      showTime = showTime.replace('SSS', '0'.repeat(3 - String(S).length) + S)
    }
    if (showTime.includes('YY')) {
      const Y = date.getFullYear()
      showTime = showTime.includes('YYYY') ? showTime.replace('YYYY', String(Y)) : showTime.replace('YY', String(Y).slice(2, 4))
    }
    if (showTime.includes('M')) {
      const M = date.getMonth() + 1
      showTime = showTime.includes('MM') ? showTime.replace('MM', fixedTwo(M)) : showTime.replace('M', String(M))
    }
    if (showTime.includes('D')) {
      const D = date.getDate()
      showTime = showTime.includes('DD') ? showTime.replace('DD', fixedTwo(D)) : showTime.replace('D', String(D))
    }
    if (showTime.includes('H')) {
      const H = date.getHours()
      showTime = showTime.includes('HH') ? showTime.replace('HH', fixedTwo(H)) : showTime.replace('H', String(H))
    }
    if (showTime.includes('m')) {
      var m = date.getMinutes()
      showTime = showTime.includes('mm') ? showTime.replace('mm', fixedTwo(m)) : showTime.replace('m', String(m))
    }
    if (showTime.includes('s')) {
      var s = date.getSeconds()
      showTime = showTime.includes('ss') ? showTime.replace('ss', fixedTwo(s)) : showTime.replace('s', String(s))
    }
    return showTime
  }
}
